package top.infopub.mgr.cap.web;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.dto.cap.ContractPledgeDto;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.cap.domain.ContractPledgeDomain;
import top.infopub.mgr.cap.jsonvo.ContractPledgeJsonVo;
import top.infopub.mgr.cap.service.CapProcessManageService;
import top.infopub.mgr.cap.service.ContractPledgeService;
import top.infopub.mgr.cap.vo.ContractPledgeVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.model.cap.ContractPledge;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
//质押合同
@Controller
@RequestMapping("/contractPledge")
public class ContractPledgeController  extends GenericFlowController {


    @Autowired
    private ContractPledgeService contractPledgeService;


    @Autowired
    private CapProcessManageService capProcessManageService;
    /**
     * 质押合同列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ContractPledgeDomain> queryDataByCondition(ContractPledgeVo contractPledgeVo,
                                                            ParamPage paramPage) {
        Page<ContractPledgeDomain> page = new Page<ContractPledgeDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        page = contractPledgeService.selectByDomainWhere(page,contractPledgeVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 根据id查询保证合同详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 保证合同Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String toDealOrDetail(HttpServletRequest request, String id, String proCode) {
        request.setAttribute("id", id);
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");//登录人和审批人一致使用该字段是否显示审核信息
        if(StringUtils.isNotEmpty(id)){
           ContractPledge contractPledge= contractPledgeService.selectByPrimaryKey(id);
            if (contractPledge != null) {
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), contractPledge.getProcessStatus())
                        || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), contractPledge.getProcessStatus())) {
                    request.setAttribute("isAuditFlag", "0");
                }
                if (StringUtils.isNotBlank(contractPledge.getProcessId()) && contractPledge.getProcessId().length() > 10) {
                    request.setAttribute("processId", contractPledge.getProcessId());
                    String auditTabFlag = capProcessManageService.checkShowAuditTab(contractPledge.getProcessId(), vo);
                    if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), contractPledge.getProcessStatus())
                            && StringUtils.equals("0", auditTabFlag)) {
                        request.setAttribute("isAuditFlag", "0");
                    }
                    request.setAttribute("auditTabFlag", auditTabFlag);
                }
            }
        }

        request.setAttribute("proCode", proCode);
        return "cap/lay-PledgeContract-detail";
    }

    @RequestMapping("/queryDetail")
    @ResponseBody
    public RspVo queryDetail(String id) {
        ContractPledgeJsonVo jsonVo = contractPledgeService.queryDetailById(id);
        return RspVo.getSuccessResponse(jsonVo);
    }

    /**
     * 编辑保证合同
     * @param bodyStr json数据
     * @param submitType 0=保存，1=提交
     * @return
     */
    @RequestMapping("/edit")
    public @ResponseBody RspVo edit(String bodyStr, Integer submitType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String str = StringEscapeUtils.unescapeJava(bodyStr);
        ContractPledgeJsonVo jsonVo = JSON.parseObject(str, ContractPledgeJsonVo.class);
        ContractPledgeDto dto = jsonVo.getInfo();

        //更新附件表-MKT_PROJECT_ATTACHMENT
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(jsonVo.getFileAtt()!=null){
            String[] fileAtt = jsonVo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(vo, dto.getProCode(), file);
                attachmentList.add(attachment);
            }
        }
        RspVo rspVo = contractPledgeService.edit(dto, jsonVo.getDetails(), attachmentList, submitType, vo);
        return rspVo;
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String processId, String status, String auditMsg, ContractPledge contractPledge) {
        //质押合同审批
        capProcessManageService.auditProject(contractPledge.getId(), processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }



    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "loanFinAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                        + filePath);
                LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD, "上传融资放款附件-文件名:" + filePath
                        + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
